# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name： flip
Description :
Author : 'li'
date： 2022/6/16
Change Activity:
2022/6/16:
-------------------------------------------------
"""
import numpy as np
import torch
import torchvision.transforms.functional as tf

from ml.dl.misc.transform import ndarray_img_to_pil


def horizontal_flip(image, target=None):
    """
    flip image horizontal.
    Args:
        image:
        target:

    Returns:

    """
    if isinstance(image, np.ndarray):
        image = ndarray_img_to_pil(image)
    flipped_image = tf.hflip(image)
    if target is None:
        return image, None
    w, h = image.size
    target = target.copy()
    if "boxes" in target:
        boxes = target["boxes"]
        boxes = boxes[:, [2, 1, 0, 3]] * torch.as_tensor([-1, 1, -1, 1]) + torch.as_tensor([w, 0, w, 0])
        target["boxes"] = boxes
    if "masks" in target:
        target['masks'] = target['masks'].flip(-1)
    return flipped_image, target


# TODO
def vertical_flip(image, target):
    """
    flip image horizontal.
    Args:
        image:
        target:

    Returns:

    """
    raise Exception('not completed.')
